package bma.shop.domain;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.JoinColumn;

@Entity
@Table(name = "PRODUCT_ORDER")
public class Order {

	private long id;
	private long amount;
	private Collection<Product> items = new ArrayList<Product>();

	@Id
	@GeneratedValue
	@Column(name = "ORDER_ID")
	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	@Column(name = "AMOUNT")
	public long getAmount() {
		return amount;
	}

	public void setAmount(long amount) {
		this.amount = amount;
	}

	public void addProduct(Product p) {
		items.add(p);
	}

	public void removeProduct(Product p) {
		for (Iterator<Product> i = items.iterator(); i.hasNext();) {
			Product item = (Product) i.next();
			if (item.getId() == p.getId()) {
				i.remove();
			}
		}
	}

	@ManyToMany(cascade = CascadeType.ALL)
	@JoinTable(name = "ORDER_TO_PRODUCT", joinColumns = { @JoinColumn(name = "orderId", referencedColumnName = "ORDER_ID") }, inverseJoinColumns = { @JoinColumn(name = "productId", referencedColumnName = "PROD_ID") })
	public Collection<Product> getProducts() {
		return new ArrayList<Product>(items);
	}

	public void setProducts(Collection<Product> p) {
		this.items = p;
	}
}
